package com.xebest.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xebest.common.enums.erp.aftersales.*;
import com.xebest.common.enums.erp.storehouse.VenStorePrintStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreReceiptStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreReceiptTypeEnum;
import com.xebest.common.enums.erp.sys.VenDelEnum;
import com.xebest.util.Money;
import com.xebest.util.seq.FinanceSeqUtil;
import com.xebest.util.seq.StoreHouseSeqUtil;
import com.xebest.web.form.*;
import com.xebest.web.mapper.read.XeVenAfterSaleDetailReadMapper;
import com.xebest.web.mapper.read.XeVenGoodsRejectDetailReadMapper;
import com.xebest.web.mapper.read.XeVenGoodsRejectReadMapper;
import com.xebest.web.mapper.write.XeVenGoodsRejectDetailWriteMapper;
import com.xebest.web.mapper.write.XeVenGoodsRejectWriteMapper;
import com.xebest.web.mapper.write.XeVenOrderRefundDetailWriteMapper;
import com.xebest.web.mapper.write.XeVenOrderRefundWriteMapper;
import com.xebest.web.model.*;
import com.xebest.web.service.XeVenGoodsRejectService;
import com.xebest.web.service.XeVenStoreReceiptService;
import com.xebest.web.view.XeVenGoodsRejectDetailView;
import com.xebest.web.view.XeVenRejectView;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @desc:
 * @author: chenjing
 * @createTime: 2017/6/22 0022 下午 4:06
 * @history:
 * @version:v1.0
 */
@Service
public class XeVenGoodsRejectServiceImpl implements XeVenGoodsRejectService {
    private static Logger log = LoggerFactory.getLogger(XeVenAfterSaleServiceImpl.class);

    @Autowired
    private XeVenGoodsRejectWriteMapper writerMapper;
    @Autowired
    private XeVenGoodsRejectReadMapper readMapper;
    @Autowired
    private XeVenOrderRefundWriteMapper refundWriteMapper;
    @Autowired
    private XeVenGoodsRejectDetailReadMapper rejectDetailReadMapper;
    @Autowired
    private XeVenOrderRefundDetailWriteMapper refundDetailWriteMapper;
    @Autowired
    private FinanceSeqUtil financeSeqUtil;
    @Autowired
    private XeVenAfterSaleDetailReadMapper afterSaleDetailReadMapper;
    @Autowired
    private XeVenGoodsRejectDetailWriteMapper rejectDetailWriteMapper;
    @Autowired
    private XeVenStoreReceiptService receiptService;


    /**
     * @Author:chenjing
     * @Description: 插入退货单信息
     * @Date:下午 4:07 2017/6/22 0022
     * @params: * @param null
     * @return:
     */
    @Override
    public int insert(XeVenGoodsRejectEntity record) {

        return writerMapper.insert(record);
    }

    /**
     * @Author:chenjing
     * @Description: 根据退货单号查询退货单信息
     * @Date:上午 11:26 2017/6/27 0027
     * @params: * @param null
     * @return:
     */
    @Override
    public XeVenGoodsRejectEntity getGoodsRejectByRejectCode(String rejectCode, String userCode) {
        return readMapper.selectByRejectCode(rejectCode, userCode);
    }

    /**
     * @Author:chenjing
     * @Description: 审核 删除退货单
     * @Date:上午 10:52 2017/6/27 0027
     * @params: * @param null
     * @return:
     */
    @Override
    public int updateGoodsReject(XeVenGoodsRejectEntity entity) throws Exception {
        //更新退货单信息

        // TODO: 2017/6/27 0027 插入退货单日志

        return writerMapper.updateByRejectInfo(entity);
    }

    /**
     * @Author:chenjing
     * @Description: 退货单确认收货
     * @Date:下午 3:35 2017/6/27 0027
     * @params: * @param null
     * @return:
     */
    @Transactional(value = "writeTransactionManager")
    @Override
    public int receiveGoodsReject(XeVenRejectSubmitForm form) throws Exception {
        int flag = 0;
        //需要更新的退货单明细列表
        List<XeVenGoodsRejectDetailEntity> rejectDetailEntities = new ArrayList<>();
        //入库单明细
        List<XeVenStoreReceiptDetailEntity> receiptDetailList = form.getList();
        //入库单号
        String receiptOrder = StoreHouseSeqUtil.seqUtils.createReceiptOrder();
        for (XeVenStoreReceiptDetailEntity detailEntity : receiptDetailList) {
            String proSku = detailEntity.getProSku();  //商品sku
            BigDecimal finishNum = detailEntity.getCurrentInNum();  //入库数量
            //退货单明细
            XeVenGoodsRejectDetailEntity entity = new XeVenGoodsRejectDetailEntity();
            entity.setFinishNum(finishNum);
            entity.setRejectCode(form.getRejectCode());
            entity.setProSku(proSku);
            rejectDetailEntities.add(entity);

//            //入库单明细
           // XeVenStoreReceiptDetailEntity receiptDetailEntity = new XeVenStoreReceiptDetailEntity();
            detailEntity.setReceiptOrder(receiptOrder); //入库单号
           // receiptDetailEntity.setProSku(proSku);   //商品sku
           // receiptDetailEntity.setBatchNo("");         //入库批次
            //detailEntity.setBatchPrice(new BigDecimal(""));      //入库批次价格
           // receiptDetailEntity.setpBatchNo("");                     //生产批次号
            //receiptDetailEntity.setProMainImg("");                   //商品图
           // receiptDetailEntity.setProNum("");                        //商品货号
           // receiptDetailEntity.setProCategoryId("");                //商品分类编码
           // receiptDetailEntity.setProCategoryName("");              //商品分类名称
          //  receiptDetailEntity.setProName("");                      //商品名称
            //receiptDetailEntity.setProUnit("");                      //商品单位
           // receiptDetailEntity.setProSepcValue("");                 //规格值
           // receiptDetailEntity.setProSpecName("");                  //规格名
           // receiptDetailEntity.setProPricingType(1);               //计量方式 1 重量  2 数量
           // receiptDetailEntity.setCurrentInNum(new BigDecimal(finishNum));      //本次入库数
           // receiptDetailEntity.setPlanInNum(new BigDecimal(finishNum));         //计划入库数

        }
        //更新退货单明细中已退货数量
        flag = rejectDetailWriteMapper.updateRejectDetailList(rejectDetailEntities);
        if(flag<=0){
            log.error("更新退货单明细失败，{}",rejectDetailEntities);
            throw  new Exception();
        }
        //生成入库单
        XeVenStoreReceiptEntity receiptEntity = new XeVenStoreReceiptEntity();
        receiptEntity.setStoreId(form.getStoreId());  //仓库id
        receiptEntity.setUserCode(form.getUserCode());
        receiptEntity.setCreateUser(form.getUserName());
        receiptEntity.setModifyUser(form.getUserName());
        receiptEntity.setReceiptOrder(receiptOrder);   //入库单号
        receiptEntity.setRelationOrder(form.getRejectCode()); //关联单号
        receiptEntity.setStoreName(form.getStoreName());  //仓库名称
        receiptEntity.setReceiptType(VenStoreReceiptTypeEnum.XSTH_RECEIPT.getValue()); //入库类型 销售退货入库
        receiptEntity.setReceiptStatus(VenStoreReceiptStatusEnum.RECEIPT.getValue());    //入库类型 已入库
        receiptEntity.setPrintStatus(VenStorePrintStatusEnum.NO.getValue());            //打印状态
        receiptEntity.setDelFlag(VenDelEnum.NO.getValue());                     //是否删除
        receiptEntity.setReceiptDetailList(receiptDetailList);
        flag = receiptService.saveStoreReceipt(receiptEntity);
        return flag;


    }

    /**
     * @Author:chenjing
     * @Description:查询退货单列表信息
     * @Date:上午 10:45 2017/7/3 0003
     * @params: * @param null
     * @return:
     */
    @Override
    public List<XeVenRejectView> queryRejectList(XeVenRejectQueryForm form) throws Exception {
        return readMapper.queryRejectList(form);
    }

    /**
     * @Author:chenjing
     * @Description:批量审核退货单
     * @Date:下午 4:05 2017/7/5 0005
     * @params: * @param null
     * @return:
     */
    @Override
    public int batchGoodsRejectList(XeVenAfterSaleCheckForm form, int rejectStatus, List checkStatusList) throws Exception {
        return writerMapper.batchGoodsRejectList(form, rejectStatus, checkStatusList);
    }

    /**
     * @Author:chenjing
     * @Description: 退货单批量确认收货
     * @Date:下午 5:26 2017/7/5 0005
     * @params: * @param null
     * @return:
     */
    @Transactional(value = "writeTransactionManager")
    @Override
    public int receiveGoodsRejectList(XeVenAfterSaleCheckForm form) throws Exception {
        int flag = 0;
        String[] formCodes = form.getFormCodes(); //退货单单号
        //查询待退货入库的退货单列表
        List<XeVenGoodsRejectEntity> rejectList = readMapper.queryRejectListByCods(form);
        //查询待退货入库的退货单明细列表
        List<XeVenGoodsRejectDetailEntity> rejectDetailList = rejectDetailReadMapper.queryRejectDetailListByCodes(formCodes);
        if (null == rejectList){
            log.error("查询退货单列表失败，{}",ToStringBuilder.reflectionToString(form));
            throw  new Exception();
        }
        if (null == rejectDetailList){
            log.error("查询退货单明细列表失败，{}",ToStringBuilder.reflectionToString(form));
            throw  new Exception();
        }
        //封装后的退款单列表信息
        List<Map<String, Object>> refundList = new ArrayList<>();
        //封装后的退款单明细信息
        List<Map<String, Object>> refundDetailList = new ArrayList<>();
        for (XeVenGoodsRejectEntity entity : rejectList) {
            //判断是否异常完成
            boolean abnormalDone = true;
            //退货单退货金额
            BigDecimal refundAmount = new BigDecimal(0);
            String refundCode = financeSeqUtil.createRefundCode();
            /**
             * 生成退款单和退款单明细
             */
            XeVenOrderRefundEntity refundEntity = new XeVenOrderRefundEntity();
            refundEntity.setAfterSalesCode(entity.getAfterSalesCode());//售后单号
            refundEntity.setOrderId(entity.getOrderId()); //订单号
            refundEntity.setRefundSource(VenOrderRefundSourceEnum.AFTER_SALE.getValue());  //退款单来源
            refundEntity.setRefundCode(refundCode);  //退款单号
            refundEntity.setRejectCode(entity.getRejectCode()); //退货单号
            refundEntity.setRefundedAmount(new BigDecimal(0)); //已退款金额
            refundEntity.setRefundType(VenOrderRefundTypeEnum.AFTERSALEREJECT.getValue());   //售后退货退款
            refundEntity.setRefundReason(VenOrderRefundReasonEnum.OTHER.getValue());//退款原因
            refundEntity.setRefundStatus(VenOrderRefundStatusEnum.PENDING.getValue()); //退款状态
            refundEntity.setCreateUser(form.getModifyUser());
            refundEntity.setModifyUser(form.getModifyUser());
            refundEntity.setDelFlag(VenDelEnum.NO.getValue());
            refundEntity.setUserCode(form.getUserCode());
            for (XeVenGoodsRejectDetailEntity detailEntity : rejectDetailList) {
                if (detailEntity.getRejectCode().equals(entity.getRejectCode())) {
                    //退货单明细退货金额
                    BigDecimal detailRefundAmount = detailEntity.getRefundAmount();
                    //退货单明细退货数量
                    BigDecimal rejectNum = detailEntity.getRejectNum();
                    if(null==detailEntity.getFinishNum()) detailEntity.setFinishNum(new BigDecimal(0));
                    //如果退货数量和已退数量不等，为异常完成
                    if (detailEntity.getRejectNum().compareTo(detailEntity.getFinishNum()) != 0) {
                        abnormalDone = false;
                        //如果异常完成，退款金额为已退货数量*商品成交价
                        detailRefundAmount = Money.of(detailEntity.getFinishNum()).multiply(detailEntity.getProCostPrice()).toStoreDecimal();
                        //异常完成退货数量为实际退货数量
                        rejectNum = detailEntity.getFinishNum();
                    }
                    //退货单退货金额
                    refundAmount = Money.of(refundAmount).plus(detailRefundAmount).toStoreDecimal();
                    //插入退款明细
                    XeVenOrderRefundDetailEntity refundDetailEntity = new XeVenOrderRefundDetailEntity();
                    refundDetailEntity.setBuyNums(detailEntity.getBuyNum());  //购买数量
                    refundDetailEntity.setProSku(detailEntity.getProSku());   //商品sku
                    refundDetailEntity.setRefundAmount(detailRefundAmount); //退货金额
                    refundDetailEntity.setRefundCode(refundCode); //退款单编码
                    refundDetailEntity.setRejectNums(rejectNum);  //退货数量
                    Map refundDetailMap = JSON.parseObject(JSON.toJSONString(refundDetailEntity, SerializerFeature.WriteMapNullValue,
                            SerializerFeature.WriteNullStringAsEmpty), Map.class);
                    refundDetailList.add(refundDetailMap);

                }
            }
            refundEntity.setRealRefundedAmount(refundAmount); //退款金额
            Map refundMap = JSON.parseObject(JSON.toJSONString(refundEntity, SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteNullStringAsEmpty), Map.class);
            refundList.add(refundMap);
            //如果退货数量和已退数量相等为正常完成，如果不相等为异常完成
            if (!abnormalDone) {
                entity.setRejectStatus(VenGoodsRejectStatusEnum.ABNORMAL_DONE.getValue());
            } else {
                entity.setRejectStatus(VenGoodsRejectStatusEnum.DONE.getValue());
            }
            entity.setModifyUser(form.getModifyUser());
        }

        //更新退货单信息
        flag = writerMapper.receiveGoodsRejectList(rejectList);
        if (flag <= 0) {
            log.error("批量更新退货单信息异常!,{}", ToStringBuilder.reflectionToString(form));
            throw new Exception();
        }

        flag = refundWriteMapper.insertAllOrderRefund(refundList);
        if (flag <= 0) {
            log.error("批量插入退款单异常!,{}", ToStringBuilder.reflectionToString(refundList));
            throw new Exception();
        }

        flag = refundDetailWriteMapper.insertAllOrderRefundDetail(refundDetailList);
        if (flag <= 0) {
            log.error("批量插入退款单明细异常! {}", ToStringBuilder.reflectionToString(refundDetailList));
            throw new Exception();
        }
        return flag;
    }

    /**
     * @Author:chenjing
     * @Description:根据退货单号查询退货单明细信息
     * @Date:下午 3:39 2017/7/6 0006
     * @params: * @param null
     * @return:
     */
    @Override
    public List<XeVenGoodsRejectDetailView> queryRejectDetail(XeVenAfterSaleDetailForm form) throws Exception {
        return rejectDetailReadMapper.getDetailListByRejcetCode(form.getRejectCode(),form.getUserCode());
    }

    /**
     * @Author:chenjing
     * @Description:批量删除退货单
     * @Date:上午 11:22 2017/7/7 0007
     * @params: * @param null
     * @return:
     */
    @Override
    public int delGoodsRejectList(XeVenAfterSaleDelForm form) {
        return writerMapper.delGoodsRejectList(form);
    }

}
